<template>
  <div class="order-list">
    <h2>我的订单</h2>

    <div class="order-filters">
      <el-select v-model="statusFilter" placeholder="订单状态" @change="handleFilterChange" clearable>
        <el-option label="全部" value="" />
        <el-option label="待付款" value="PENDING" />
        <el-option label="已付款" value="PAID" />
        <el-option label="已发货" value="SHIPPED" />
        <el-option label="已完成" value="COMPLETED" />
        <el-option label="已取消" value="CANCELLED" />
      </el-select>

      <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateChange"
      />
    </div>

    <div v-loading="loading">
      <div v-if="orders.length === 0" class="empty-orders">
        <el-empty description="暂无订单" />
      </div>

      <div v-else class="orders-container">
        <el-card v-for="order in orders" :key="order.id" class="order-card">
          <div class="order-header">
            <div class="order-info">
              <span class="order-id">订单号：{{ order.orderNumber }}</span>
              <span class="order-date">{{ formatDate(order.orderDate) }}</span>
              <span class="username">用户：{{ order.username }}</span>
            </div>
            <el-tag :type="getStatusType(order.orderStatus)">
              {{ getStatusText(order.orderStatus) }}
            </el-tag>
          </div>

          <div class="order-items">
            <div class="order-item">
              <img :src="order.product?.imageUrl || defaultProductImage" class="item-image" />
              <div class="item-info">
                <h4>{{ order.product?.name }}</h4>
                <p class="item-price">¥{{ order.product?.price }}</p>
                <p class="item-quantity">x{{ order.quantity }}</p>
                <p class="item-points">积分: {{ order.orderPoints }}</p>
              </div>
            </div>
          </div>

          <div class="order-details">
            <div class="detail-row">
              <span class="detail-label">收货地址：</span>
              <span>{{ order.address }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">联系方式：</span>
              <span>{{ order.contactPhone }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">支付方式：</span>
              <span>{{ getPaymentMethodText(order.paymentMethod) }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">运送方式：</span>
              <span>{{ getShippingMethodText(order.shippingMethod) }}</span>
            </div>
            <div v-if="order.remarks" class="detail-row">
              <span class="detail-label">备注：</span>
              <span>{{ order.remarks }}</span>
            </div>
            <div class="detail-row" v-if="order.discountRate">
              <span class="detail-label">折扣信息：</span>
              <span v-if="order.discountRate === 0.8">
                <el-tag type="success">生日特权：8折+积分翻倍</el-tag>
              </span>
              <span v-else>
                会员折扣：{{ (order.discountRate * 100).toFixed(0) }}%
              </span>
            </div>
            <div class="detail-row" v-if="order.discountAmount">
              <span class="detail-label">优惠金额：</span>
              <span>¥{{ order.discountAmount }}</span>
            </div>
          </div>

          <div class="order-footer">
            <div class="order-total">
              <span>总计：</span>
              <span class="total-price">¥{{ order.totalAmount }}</span>
              <span class="total-points">(获得积分: {{ order.pointsAwarded || order.orderPoints }})</span>
              <span v-if="order.discountRate">
                <el-tag size="mini" v-if="order.discountRate === 0.8">生日特权</el-tag>
                <el-tag size="mini" v-else>会员折扣</el-tag>
              </span>
            </div>
            <div class="order-actions">
              <template v-if="order.orderStatus === 'PENDING'">
                <el-button type="primary" @click="handlePay(order)">立即付款</el-button>
                <el-button @click="handleCancel(order)">取消订单</el-button>
              </template>
              <template v-if="order.orderStatus === 'SHIPPED'">
                <el-button type="success" @click="handleConfirmReceipt(order)">确认收货</el-button>
              </template>
              <template v-if="order.orderStatus === 'COMPLETED'">
                <el-button type="primary" @click="handleReview(order)">评价</el-button>
              </template>
            </div>
          </div>
        </el-card>
      </div>

      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 支付对话框 -->
    <el-dialog v-model="payDialogVisible" title="订单支付" width="400px">
      <div class="payment-info">
        <p>订单号：{{ currentOrder?.orderNumber }}</p>
        <p>支付金额：¥{{ currentOrder?.totalAmount }}</p>
        <p>获得积分：{{ currentOrder?.orderPoints }}</p>
      </div>
      <div class="payment-methods">
        <el-radio-group v-model="paymentMethod">
          <el-radio label="ALIPAY">支付宝</el-radio>
          <el-radio label="WECHAT">微信支付</el-radio>
          <el-radio label="CREDIT_CARD">信用卡</el-radio>
          <el-radio label="DEBIT_CARD">借记卡</el-radio>
          <el-radio label="CASH">现金</el-radio>
          <el-radio label="BANK_TRANSFER">银行转账</el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="payDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPayment" :loading="submitting">
            确认支付
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 评价对话框 -->
    <el-dialog v-model="reviewDialogVisible" title="商品评价" width="500px">
      <div class="review-item">
        <div class="review-product">
          <img :src="currentOrder?.product?.imageUrl || defaultProductImage" class="review-image" />
          <span>{{ currentOrder?.product?.name }}</span>
        </div>
        <div class="review-form">
          <div class="rating-item">
            <span class="rating-label">商品评分：</span>
            <el-rate v-model="reviewRating" :max="5" />
          </div>
          <el-input
              v-model="reviewContent"
              type="textarea"
              :rows="3"
              placeholder="请输入您的评价..."
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="submitting">
            提交评价
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserOrders, cancelOrder, updateOrderStatus } from '@/api/order'
import { addComment } from '@/api/comment'
import defaultProductImage from '@/assets/images/default-product.jpg'

// 导入商品图片
import javaBookImage from '@/assets/images/Java编程思想.jpg'
import iphoneImage from '@/assets/images/iphone 15 Pro.jpg'
import nikeImage from '@/assets/images/Nike Air Max.jpg'

// 商品图片映射
const productImages = {
  'Java编程思想.jpg': javaBookImage,
  'iphone 15 Pro.jpg': iphoneImage,
  'Nike Air Max.jpg': nikeImage
}

const router = useRouter()
const loading = ref(false)
const submitting = ref(false)
const orders = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const statusFilter = ref('')
const dateRange = ref([])

const payDialogVisible = ref(false)
const reviewDialogVisible = ref(false)
const currentOrder = ref(null)
const paymentMethod = ref('')
const reviewContent = ref('')
const reviewRating = ref(5)

onMounted(async () => {
  await loadOrders()
})

const loadOrders = async () => {
  loading.value = true
  try {
    const res = await getUserOrders()
    orders.value = res.data
  } catch (error) {
    console.error(error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

const handleFilterChange = () => {
  currentPage.value = 1
  loadOrders()
}

const handleDateChange = () => {
  currentPage.value = 1
  loadOrders()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadOrders()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadOrders()
}

const handlePay = (order) => {
  currentOrder.value = order
  paymentMethod.value = ''
  payDialogVisible.value = true
}

const handleCancel = async (order) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      type: 'warning'
    })
    await cancelOrder(order.id)
    ElMessage.success('订单已取消')
    await loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('取消订单失败')
    }
  }
}

const handleConfirmReceipt = async (order) => {
  try {
    await ElMessageBox.confirm('确认已收到商品？', '提示', {
      type: 'warning'
    })
    await updateOrderStatus(order.id, 'COMPLETED')
    ElMessage.success('确认收货成功')
    await loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('确认收货失败')
    }
  }
}

const handleReview = (order) => {
  currentOrder.value = order
  reviewContent.value = ''
  reviewRating.value = 5
  reviewDialogVisible.value = true
}

const submitPayment = async () => {
  if (!paymentMethod.value) {
    ElMessage.warning('请选择支付方式')
    return
  }

  submitting.value = true
  try {
    await updateOrderStatus(currentOrder.value.id, 'PAID')
    ElMessage.success('支付成功')
    payDialogVisible.value = false
    await loadOrders()
  } catch (error) {
    console.error(error)
    ElMessage.error('支付失败')
  } finally {
    submitting.value = false
  }
}

const submitReview = async () => {
  if (!reviewContent.value.trim()) {
    ElMessage.warning('请输入评价内容')
    return
  }

  if (reviewRating.value < 1 || reviewRating.value > 5) {
    ElMessage.warning('请选择1-5之间的评分')
    return
  }

  submitting.value = true
  try {
    await addComment({
      productId: currentOrder.value.product.id,
      content: reviewContent.value.trim(),
      rating: reviewRating.value,
      orderId: currentOrder.value.id
    })
    ElMessage.success('评价成功')
    reviewDialogVisible.value = false
    await loadOrders()
  } catch (error) {
    console.error(error)
    ElMessage.error(error.response?.data?.message || '评价失败')
  } finally {
    submitting.value = false
  }
}

const getStatusType = (status) => {
  const types = {
    PENDING: 'warning',
    PAID: 'info',
    SHIPPED: 'primary',
    COMPLETED: 'success',
    CANCELLED: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    PENDING: '待付款',
    PAID: '已付款',
    SHIPPED: '已发货',
    COMPLETED: '已完成',
    CANCELLED: '已取消'
  }
  return texts[status] || status
}

const getPaymentMethodText = (method) => {
  const texts = {
    ALIPAY: '支付宝',
    WECHAT: '微信支付',
    CREDIT_CARD: '信用卡',
    DEBIT_CARD: '借记卡',
    CASH: '现金',
    BANK_TRANSFER: '银行转账'
  }
  return texts[method] || method
}

const getShippingMethodText = (method) => {
  const texts = {
    EXPRESS: '快递',
    STANDARD: '标准配送',
    PICKUP: '自提'
  }
  return texts[method] || method
}

const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

// 获取商品图片URL
const getProductImageUrl = (product) => {
  if (!product || !product.imageUrl) {
    return defaultProductImage
  }

  // 从商品图片映射中获取图片
  const imageName = product.imageUrl.split('/').pop()
  return productImages[imageName] || defaultProductImage
}
</script>

<style scoped>
.order-list {
  padding: 20px;
}

.order-filters {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.empty-orders {
  padding: 40px 0;
  text-align: center;
}

.orders-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-card {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.order-info {
  display: flex;
  gap: 20px;
}

.order-id {
  font-weight: bold;
}

.order-date {
  color: #666;
}

.username {
  color: #666;
}

.order-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.order-item {
  display: flex;
  gap: 15px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-info h4 {
  margin: 0 0 8px 0;
}

.item-price {
  color: #f56c6c;
  font-weight: bold;
  margin: 0;
}

.item-quantity {
  color: #666;
  margin: 0;
}

.item-points {
  color: #67c23a;
  margin: 0;
}

.order-details {
  margin: 15px 0;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.detail-row {
  display: flex;
  margin-bottom: 8px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-label {
  font-weight: bold;
  width: 100px;
  flex-shrink: 0;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.order-total {
  font-size: 16px;
}

.total-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-left: 8px;
}

.total-points {
  color: #67c23a;
  font-size: 14px;
  margin-left: 8px;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.payment-info {
  margin-bottom: 20px;
}

.payment-info p {
  margin: 10px 0;
}

.payment-methods {
  margin-bottom: 20px;
}

.review-item {
  margin-bottom: 20px;
}

.review-product {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.review-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.review-form {
  margin-top: 15px;
}

.rating-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.rating-label {
  margin-right: 10px;
  color: #606266;
}
</style> 